/**
 * 获取所有路由页面
 */
function addRoutePage() {
  const allRouters = []
  //获取所有路由页面
  const files = import.meta.glob('@/router/main/**/*.js', {
    eager: true
  })
  for (const fileKey in files) {
    const file = files[fileKey]
    allRouters.push(file.default)
  }
  return allRouters
}

/**
 * 动态注册路由信息
 * @returns {*[]}
 * @param userMenus
 */
export default function registerRouter(userMenus) {
  const allRouters = addRoutePage()
  //查找符合路由的path
  const routes = []
  for (const userMenu of userMenus) {
    for (const childrenMenu of userMenu.children) {
      //找到的路由
      const findPath = allRouters.find((item) => item.path === childrenMenu.component)
      if (findPath) {
        routes.push(findPath)
      }
    }
  }
  return routes
}

//查找激活的菜单数据
export function activeRouter(path, userMenus) {
  if (path === '/main/home') {
    return 0 + ''
  }
  for (const userMenu of userMenus) {
    for (const childMenu of userMenu.children) {
      if (childMenu.component === path) {
        return childMenu.menuId + ''
      }
    }
  }
}

/**
 * 面包屑导航栏
 * @param path
 * @param userMenus
 */
export function breadPathName(path, userMenus) {
  const breadPathNames = []
  if (path === '/main/home') {
    breadPathNames.push(
      {
        path: '/main/home',
        name: '首页'
      },
      {
        path: '',  // 空路径表示纯文本
        name: '欢迎来到飞羽行迹',
        isWelcome: true  // 可选的自定义标识
      }
    )
    return breadPathNames
  }
  if (path === '/main/person') {
    breadPathNames.push({
      path: '/main/person',
      name: '个人中心'
    })
    return breadPathNames
  }
  for (const userMenu of userMenus) {
    for (const userMenuChildren of userMenu.children) {
      if (userMenuChildren.component === path) {
        //添加父级菜单名称
        breadPathNames.push({
          path: userMenu.component,
          name: userMenu.menuName
        })
        //添加子级菜单名称
        breadPathNames.push({
          path: userMenuChildren.component,
          name: userMenuChildren.menuName
        })
      }
    }
  }

  return breadPathNames
}
